package stu.aistar.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.lettuce.core.ScriptOutputType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;;
import org.springframework.web.bind.annotation.*;
import stu.aistar.model.pojo.User;
import stu.aistar.model.vo.Result;
import stu.aistar.service.UserService;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    /**
     * 跳转登录页
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "sign-in";
    }

    /**
     * 跳转注册页
     * @return
     */
    @GetMapping("/register")
    public String toRegister(){
        return "sign-up";
    }

    /**
     * 检查手机号是否被注册
     * @param phone
     * @return
     */
    @RequestMapping("/isExistPhone")
    @ResponseBody
    public Result isExistPhone(@RequestParam("phone") String phone){
        Result result = null;
        User user = userService.findUserByPhone(phone);
        if(null == user){
            result = new Result("200","手机号未被注册",null);
        }else {
            result = new Result("404","手机已被注册",null);
        }
        return result;
    }

    /**
     * 发送验证码
     * @param phoneNumber
     * @param request
     * @return
     */
    @PostMapping("/sendCode")
    @ResponseBody
    public Result getCode(@RequestParam("phone") String phoneNumber, HttpServletRequest request) {
        Map<String,String> map = new HashMap<>();
        map.put("apiUrl","https://sms_developer.zhenzikj.com");
        map.put("appId","108900");
        map.put("appSecret","797d6d93-fadf-4d6a-ba4e-543723a36a88");
        map.put("templateId","4998");
        map.put("timeOut","1");
        try{
            String code = userService.sendVerifyCode(phoneNumber, 6, map);
            // 将验证码存入redis缓存中,时效60s
            redisTemplate.opsForValue().set(phoneNumber+"_code",code,60, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set("phone",phoneNumber,60,TimeUnit.SECONDS);
            return new Result("200","发送成功",null);
        }catch(Exception e){
            e.printStackTrace();
            return new Result("500",e.getMessage(),null);
        }
    }

    /**
     * 用户注册
     * @param request
     * @param phone
     * @param password
     * @param code
     * @return
     */
    @RequestMapping("/registerUser")
    @ResponseBody
    public Result register(HttpServletRequest request,@RequestParam("phone")String phone,@RequestParam("password") String password,@RequestParam("code")String code){
        Result result = null;
        //获取生成的验证码
        String send_code = redisTemplate.opsForValue().get(phone + "_code");
        String recv_phone = redisTemplate.opsForValue().get("phone");
        if(code.equals(send_code)&&phone.equals(recv_phone)){
            result = new Result("200","验证码正确",null);
            //用户注册
            userService.registUser(phone, password);
        }else if(null == send_code){
            //验证码过期
            result = new Result("404","验证码失效",null);
        }else{
            result = new Result("500","验证码错误",null);
        }

        return result;
    }

    /**
     * 实现用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(User user){
        System.out.println(user);
        User loginUser = userService.login(user.getPhone(), user.getPassword());
        Result result = null;
        if (null == loginUser){
            result = new Result("404","手机号或密码错误",null);
        }else {
            //将用户信息存放到redis中
            redisTemplate.opsForValue().set("user_"+user.getPhone(), String.valueOf(loginUser));
            result = new Result("200","登录成功",null);
        }
        return result;
    }

    /**
     * 跳转到主页
     * @return
     */
    @RequestMapping("/index")
    public String index(){
        return "index";
    }


    /**
     * 分页查询+条件查询
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/admin/getUserInfo")
    @ResponseBody
    public Map<String,Object> getUserInfo(HttpServletRequest request){
        String page = request.getParameter("page");
        String pageSize = request.getParameter("limit");
        String params = request.getParameter("searchParams");
        String name = null;
        String username=null;
        String phone=null;
        //先转换成JSONObject类型
        if (null != params){
            JSONObject obj = JSONObject.parseObject(params);
            name= obj.getString("name");
            username = obj.getString("username");
            phone = obj.getString("phone");
        }
        Map<String,Object> userMap = new HashMap<>();
        PageInfo<User> users = userService.findUsersByPage(page,pageSize,username,phone,name);
        users.getList().forEach(e-> System.out.println(e));
        userMap.put("code",0);
        userMap.put("msg","查找成功");
        //数据总数
        userMap.put("count",users.getTotal());
        userMap.put("data",users.getList());
        return userMap;
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @RequestMapping("/admin/delUserById")
    @ResponseBody
    public Result delUserById(@RequestParam("id") Integer id){
        int row = userService.delUserById(id);
        Result result = null;
        if (row == 0){
            result = new Result("500","删除失败","");
        }else {
            result = new Result("200","删除成功","");
        }
        return result;
    }


    @RequestMapping("/admin/editUser")
    @ResponseBody
    public Result updateUser(@RequestBody User user){
        System.out.println("================================================");
        System.out.println(user.toString());
        int row = userService.updateUser(user);
        Result result = null;
        if (row == 0){
            result = new Result("500","修改失败","");
        }else {
            result = new Result("200","修改成功","");
            System.out.println(result);
        }
        return result;
    }
}
